package com.xc.helloworld;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * @Package com.xc.helloworld
 * @Description 客户端启动类
 * @Author kunshan
 * @Date 2021/1/26 5:44 下午
 */
public class AppClientHello {
    private final String host;
    private final int  port;

    public AppClientHello(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception{

        NioEventLoopGroup group = new NioEventLoopGroup();   //IO线程池
        try{
            Bootstrap bs = new Bootstrap(); //客户端辅助启动类
            bs.group(group)
                    .channel(NioSocketChannel.class)   //实例化一个channel
                    .remoteAddress(new InetSocketAddress(host,port))
                    .handler(new NettyClientFilter());
            // 配置完成后，链接到远端
            // 连接到远程节点，等待链接完成
            ChannelFuture future = bs.connect().sync();

            //发送消息到服务器，格式是UTF-8
            //future.channel().writeAndFlush(Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8));
            System.out.println("发送消息");
            future.channel().writeAndFlush("hello world\n");

            // 阻塞操作，closeFuture() 开启了一个channel的监听器，（这期间channel在进行各项工作，直到链接断开）
            future.channel().closeFuture().sync();
        } finally {
            //最后要释放资源，释放线程池后，彻底关闭，防止内存溢出
            //优雅的关闭线程池
            group.shutdownGracefully().sync();
        }

    }

    //启动
    public static void main(String[] args) throws Exception{
        new AppClientHello("127.0.0.1",6789).run();
    }
}
